package com.github.zxhTom.demo.mina.service;

import com.github.zxhTom.demo.mina.Constaint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @author zxh
 */
public class Service {
    /**
     * 日志处理
     */
    private static Logger logger = LogManager.getLogger(Service.class);

    public static void main(String[] args) {
        //创建监听对象
        IoAcceptor acceptor = new NioSocketAcceptor();
        TextLineCodecFactory textLineCodecFactory =
                new TextLineCodecFactory(Charset.forName("utf-8"), LineDelimiter.WINDOWS.getValue(),
                        LineDelimiter.WINDOWS.getValue());
        //添加过滤器
        acceptor.getFilterChain().addLast("logger",new LoggingFilter());
        acceptor.getFilterChain().addLast("protocal",new ProtocolCodecFilter(
                textLineCodecFactory
        ));
        //设置时间处理的handler
        acceptor.setHandler(new ServerMessageHandler());
        //设置读取数据缓存区的大小
        acceptor.getSessionConfig().setReadBufferSize(Constaint.READSIZE);
        //设置多久没有消息就进入空闲状态
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,Constaint.IDLETIME);
        //绑定端口
        try {
            acceptor.bind(new InetSocketAddress(Constaint.REMOTE_PORT));
        } catch (IOException e) {
            logger.error(String.format("bind %s error",Constaint.REMOTE_PORT));
            e.printStackTrace();
        }
        logger.info(String.format("bind %s success",Constaint.REMOTE_PORT));
    }
}

